//
//  MTTargetType+Default.swift
//  MT
//
//  Created by zhang qiang on 2019/4/28.
//  Copyright © 2019 DDC. All rights reserved.
//

import Foundation
import Moya


/// 在这里处理默认值, 相当于以此封装
public extension MTTargetType {
    
    var headers: [String : String]? {
        var params: [String : String] = ["Content-type": "application/json"]
        params.merge(self.defaultHeaderParam.map { $0 }) { (old, _) in old }
        
        return params
    }
    
    var baseURL: URL {
        return URL(string: "")!
    }
    
    var method: Moya.Method {
        return .post
    }
    
    var sampleData: Data {
        return "".data(using: String.Encoding.utf8)!
    }
    
    var authorizationType: AuthorizationType {
        return AuthorizationType.bearer
    }
    
    var task: Task {
        var params: [String : Any] = self.params ?? [:]
        params.merge(self.defaultParam.map { $0 }) { (old, _) in old }
        
        switch self.method {
        case .get:
            return Task.requestCompositeData(bodyData: Data(), urlParameters: params)
        default:
            return .requestParameters(parameters: params, encoding: JSONEncoding.default)
        }
        
    }
    
    var needCache: Bool {
        return false
    }
    
    var cachePolicy: RequestCachePolicy {
        return .reloadIgnoringLocalCacheData
    }
    
    var cacheId: () -> String {
        return { self.path }
    }
}

// MARK: - DDCTargetType 默认参数
extension MTTargetType {
    
    /// 默认请求参数
    public var defaultParam: [String: Any] {
        let params: [String: Any] = [:]
        //params["os"] = "ios"
        //params["time"] = timestamp
        return params
    }
    
    /// 默认请求头参数
    public var defaultHeaderParam: [String: String] {
        let params: [String: String] = [:]
//        params["platform"] = "iOS"
//        params["version"] = "1.1.1" // 当前软件版本
//        params["deviceType"] = Device().description // 设备类型 Device.identifier // such as "iPhone7, 1"
//        params["osVersion"] = Device().systemVersion // iOS 系统 版本号
        return params
    }
    
    /// 时间戳
    public var timestamp: String {
        let date = NSDate()
        let timeInterval = date.timeIntervalSince1970 * 1000
        return String(format: "%.0f", timeInterval)
    }
}

